package com.cartrentalsystem.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cartrentalsystem.domain.po.Employee;
import com.cartrentalsystem.domain.vo.EmployeeVo;
import com.cartrentalsystem.domain.vo.Result;
import com.cartrentalsystem.mapper.EmployeeMapper;
import com.cartrentalsystem.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cartrentalsystem.utils.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LHD
 * @since 2025-06-16
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    private final RedisTemplate redisTemplate;

    @Override
    public Result<Page<Employee>> pageList(Integer page, Integer size, Integer role, String name, Integer status){
        Page<Employee> list = new Page<>(page, size);
        Page<Employee> page1 = this.lambdaQuery()
                .eq(role != null, Employee::getRole, role)
                .like(name != null, Employee::getName, name)
                .eq(status != null, Employee::getStatus, status)
                .eq(Employee::getDeleted, 0)
                .page(list);
        return Result.success(page1);
    }

    @Override
    public Result<String> addEmployee(Employee employee){
        employee.setDeleted(0);
        return this.save(employee) ? Result.success("添加成功") : Result.fail("添加失败");
    }

    @Override
    public Result<String> updateEmployee(Employee employee){
        return this.updateById(employee) ? Result.success("修改成功") : Result.fail("修改失败");
    }

    @Override
    @Transactional
    public Integer getIdByNameAndRole(String employeeName, Integer role){
        Employee one = this.lambdaQuery()
                .eq(Employee::getName, employeeName)
                .eq(Employee::getRole, role)
                .select(Employee::getId)
                .one();
        return one.getId();
    }

    @Override
    public EmployeeVo login(String username, String password, String uuid, String code, HttpServletResponse response){
        Employee employee = this.lambdaQuery()
                .eq(Employee::getUsername, username)
                .one();
                if (employee == null){
                    throw new RuntimeException("用户名或密码错误");
                }
                if (!employee.getPassword().equals(password)){
                    throw new RuntimeException("用户名或密码错误");
                }

        String redisCode = (String) redisTemplate.opsForValue().get("Captcha" + uuid);
        if (redisCode == null){
            throw new RuntimeException("验证码已过期");
        }
        if (!redisCode.equals(code)){
            throw new RuntimeException("验证码错误");
        }
        log.info("员工登录成功：{}", employee);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", employee.getId());
        String jwt = JwtUtil.createJWT("LHD", 7200000, claims);
        log.info("生成jwt：{}", jwt);
        response.setHeader("Token", jwt);

        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(employee, employeeVo);
        employeeVo.setToken(jwt);
        log.info("用户信息：{}", employee);
        log.info("用户信息：{}", employeeVo);
        redisTemplate.opsForHash().put("employeeId:"+employee.getId(), "Employee", employeeVo);
        return employeeVo;
    }
}
